/**
 * useElementPlusModal - 基于Element-Plus的纯组合式函数实现
 *
 * 完全通过组合式函数实现弹窗打开URL功能，无需额外组件
 *
 * @param {Object} app - Vue应用实例
 * @returns {Object} 返回弹窗控制方法
 */

import { h, render } from 'vue';
import { ElDialog } from 'element-plus';

export function useElementPlusModal(app) {
  /**
   * 打开URL弹窗
   * @param {Object} options - 配置选项
   * @param {string} options.url - 要打开的URL
   * @param {string} options.title - 弹窗标题
   * @param {string} options.width - 弹窗宽度，默认'70%'
   * @param {string} options.height - 弹窗高度，默认'80vh'
   * @param {boolean} options.fullscreen - 是否全屏，默认false
   * @param {Function} options.onClose - 关闭回调
   * @returns {Object} 返回控制方法
   */
  const openUrlModal = (options = {}) => {
    const {
      url = '',
      title = '页面预览',
      width = '70%',
      height = '70vh',
      fullscreen = false,
      onClose = () => {},
    } = options;

    // 处理URL，添加nolayout参数
    const processUrl = (rawUrl) => {
      if (!rawUrl) return '';

      try {
        const host = window.location.origin;
        const hasQuery = rawUrl.includes('?');
        const separator = hasQuery ? '&' : '?';

        return `${host}/#${rawUrl}${separator}nolayout=1`;
      } catch (error) {
        console.error('处理URL失败:', error);
        return rawUrl;
      }
    };

    const targetUrl = processUrl(url);
    let isVisible = true;
    let container = null;

    // 创建弹窗内容
    const createModalContent = () => {
      return h('div', { style: { height: '100%' } }, [
        !targetUrl
          ? h(
              'div',
              {
                style: {
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  height: '100%',
                  color: '#999',
                  fontSize: '14px',
                },
              },
              '未提供有效的URL',
            )
          : h('iframe', {
              src: targetUrl,
              style: {
                width: '100%',
                height: '100%',
                border: 'none',
                display: 'block',
              },
              frameborder: '0',
              onLoad: () => {
                console.log('iframe加载完成');
              },
              onError: (error) => {
                console.error('iframe加载失败:', error);
              },
            }),
      ]);
    };

    // 创建弹窗组件
    const createModal = () => {
      return h(
        ElDialog,
        {
          modelValue: isVisible,
          title: title,
          width: width,
          fullscreen: fullscreen,
          destroyOnClose: true,
          closeOnClickModal: false,
          closeOnPressEscape: true,
          showClose: true,
          draggable: true,
          'onUpdate:modelValue': (value) => {
            isVisible = value;
            if (!value) {
              closeModal();
            }
          },
          onClose: () => {
            onClose();
            closeModal();
          },
          style: {
            '--el-dialog-content-font-size': '14px',
          },
        },
        {
          default: () =>
            h(
              'div',
              {
                style: {
                  height: fullscreen ? 'calc(100vh - 120px)' : height,
                  overflow: 'hidden',
                },
              },
              [createModalContent()],
            ),
        },
      );
    };

    // 关闭弹窗
    const closeModal = () => {
      if (container) {
        render(null, container);
        document.body.removeChild(container);
        container = null;
      }
    };

    // 渲染弹窗
    const renderModal = () => {
      container = document.createElement('div');
      document.body.appendChild(container);

      const vnode = createModal();
      vnode.appContext = app._context;
      render(vnode, container);
    };

    // 立即渲染
    renderModal();

    // 返回控制方法
    return {
      close: closeModal,
      updateUrl: (newUrl) => {
        // 更新URL并重新渲染
        options.url = newUrl;
        if (container) {
          const vnode = createModal();
          vnode.appContext = app._context;
          render(vnode, container);
        }
      },
    };
  };

  /**
   * 快速打开URL弹窗的便捷方法
   * @param {string} url - URL地址
   * @param {string} title - 弹窗标题
   * @returns {Object} 控制方法
   */
  const openUrl = (url, title = '页面预览') => {
    return openUrlModal({ url, title });
  };

  /**
   * 打开全屏URL弹窗
   * @param {string} url - URL地址
   * @param {string} title - 弹窗标题
   * @returns {Object} 控制方法
   */
  const openUrlFullscreen = (url, title = '页面预览') => {
    return openUrlModal({
      url,
      title,
      fullscreen: true,
    });
  };

  return {
    openUrlModal,
    openUrl,
    openUrlFullscreen,
  };
}
